//
//  RealityController.m
//  敢唆嘛!
//
//  Created by 教主 on 15/11/23.
//  Copyright © 2015年 zms. All rights reserved.
//

#import "RealityController.h"
#import "RealityCell.h"
#import "Device.h"
#import "Define.h"
#import "DetailController.h"
#import "RealityModel.h"
#import "RealityHeader.h"

//界面的状态枚举值
typedef NS_ENUM(NSInteger, HotOrNewState)
{
    hot,
    new
};

@interface RealityController ()<UITableViewDataSource,UITableViewDelegate>
{
    // 最新和最热模式切换
    HotOrNewState hotOrNewState;
}
@property(nonatomic , strong)UITableView *tableView;
@property(nonatomic , strong)NSMutableArray *realityArray;

@end
static NSString *cellIndentifier = @"cell";
@implementation RealityController
{
    CGFloat height;
    NSInteger limitNumber;  // 分页查询记录
    NSString *typeName;     // 记录类型
}

// 返回是哪个表的数据
- (NSString *)tableClassName
{
    NSString *className = nil;
#warning 判断页面
    if (self.isReality)
    {
        className = @"Reality";
    }
    else if (self.isCreation)
    {
        className = @"Creation";
    }
    else if (self.isTravel)
    {
        className = @"Travel";
    }
    else
    {
        className = @"Secret";
    }
    return className;
}

// 查询bmob数据库表内所有内容 最多1000 默认100
- (void)findAllRealityData:(NSInteger)limit
{
    BmobQuery *bquery = [BmobQuery queryWithClassName:[self tableClassName]];
    bquery.limit = limit;
    if (hotOrNewState == new)
    {
        [bquery orderByDescending:@"createdAt"];
    }
    else
    {
        [bquery orderByDescending:@"commentNumber"];
    }
    
    //查找Reality表的数据
    [bquery findObjectsInBackgroundWithBlock:^(NSArray *array, NSError *error) {
        if (error)
        {
            // 判断网络连接
            if (![[NetWorkState shareInstance] reachability])
            {
                [self alertActionWithTitle:@"提示" message:@"网络不通" other:@"确定"];
            };
            NSLog(@"error:%@",error);
        }
        else
        {
            // 数据请求成功后才初始化数组 否则会造成下拉刷新崩溃
            self.realityArray = [NSMutableArray array];
            for (BmobObject *obj in array)
            {
                RealityModel *model = [[RealityModel alloc] initWithObj:obj];
                // 条用单条查询 来获取用户头像
                [self findUserDataWith:model];
                [self.realityArray addObject:model];
            }
            // 需要在主线程里面进行刷新
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadData];
                [self.tableView.header endRefreshing];
                [self.tableView.footer endRefreshing];
            });
        }
    }];
}

// 查询bmob数据库表内所有内容 最多1000 默认100  查找用户
- (void)findUserDataWith:(RealityModel *)model
{
    BmobQuery *bquery = [BmobQuery queryWithClassName:@"_User"];
    bquery.limit = 1000;
    //查找Recommend表的数据
    [bquery findObjectsInBackgroundWithBlock:^(NSArray *array, NSError *error) {
        if (error)
        {
            // 判断网络连接
            if (![[NetWorkState shareInstance] reachability])
            {
                [self alertActionWithTitle:@"提示" message:@"网络不通" other:@"确定"];
            };
            NSLog(@"error:%@",error);
        }
        else
        {
            for (BmobObject *obj in array)
            {
                // 得到用户的头像
                if ([model.userName isEqualToString:[obj objectForKey:@"username"]])
                {
                    BmobFile *userHeaderFile = [obj objectForKey:@"userHeader"];
                    model.userHeader = userHeaderFile.url;
                }
            }
            // 需要在主线程里面进行刷新
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadData];
            });
        }
    }];
}

- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBar.translucent = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];

//    cell的高度
    height = KSHeight/1.75;
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, KSWidth, KSHeight - 64) style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor whiteColor];
    [self.tableView registerClass:[RealityCell class] forCellReuseIdentifier:cellIndentifier];
    [self.tableView registerClass:[RealityHeader class] forHeaderFooterViewReuseIdentifier:@"header"];
    [self.view addSubview:self.tableView];
    
    // 默认是最新
    hotOrNewState = new;
    
    // 分页默认为10
    limitNumber = 10;
    // 调用数据查询
    [self findAllRealityData:limitNumber];
    
    // 添加下拉刷新
    [self.tableView addLegendHeaderWithRefreshingTarget:self refreshingAction:@selector(headerRefreshing)];
    
    // 添加上拉加载更多
    [self.tableView addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(footerRefreshing)];
}

// 下拉刷新
- (void)headerRefreshing
{
    // 刷新调用
    [self findAllRealityData:limitNumber];
}

// 上拉加载更多
- (void)footerRefreshing
{
    limitNumber += 5;
    // 刷新调用
    [self findAllRealityData:limitNumber];
}

// 返回分区
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

//返回行数
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.realityArray.count;
}

//cell 的高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [RealityCell heightForCell:self.realityArray[indexPath.row]];
}

//返回cell
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    RealityCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndentifier forIndexPath:indexPath];
    
    RealityModel *model = self.realityArray[indexPath.row];
    typeName = model.type;
    cell.model = model;
    
    return cell;
}


//点击cell
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    DetailController *detailVc = [[DetailController alloc]init];
    
    detailVc.realityModel = self.realityArray[indexPath.row];
    
    [self.navigationController pushViewController:detailVc animated:YES];
    
}

// 设置tableview表头高度
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return height/5;
}

// 表头设置
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    RealityHeader *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"header"];

    // 平移手势
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panAction:)];
    
    [header.whiteView addGestureRecognizer:pan];
    
    
    if ([typeName isEqualToString:@"真事"])
    {
        header.titleLabel.text = @"事实是一种倔强的东西";
    }
    else if ([typeName isEqualToString:@"创作"])
    {
        header.titleLabel.text = @"做一个白日梦好了";
    }
    else if ([typeName isEqualToString:@"游记"])
    {
        header.titleLabel.text = @"衣上征尘杂酒痕,远游无处不消魂";
    }
    else if ([typeName isEqualToString:@"秘密"])
    {
        header.titleLabel.text = @"独自度过的内心是孤独,也是海洋";
    }
    
    return header;

}

//设置表尾高度
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}

// 平移手势事件
-(void)panAction:(UIPanGestureRecognizer *)pan
{
//    取到手势的位置坐标
     CGPoint point = [pan translationInView:pan.view];
    NSLog(@"x=%f,y=%f",point.x,point.y);
//    把中心点的Y坐标固定
    point.y = 0;
// 设置中心点X坐标的最小滑动位置
    CGFloat centerX  = KSWidth/8;
    
    pan.view.center = CGPointMake(pan.view.center.x +point.x,pan.view.center.y + point.y);
    
    if (pan.view.center.x <= KSWidth/8)
    {
        pan.view.center = CGPointMake(centerX,pan.view.center.y + point.y);
    }
    else if(pan.view.center.x >= KSWidth/8*3)
    {
        pan.view.center = CGPointMake(centerX*3,pan.view.center.y + point.y);
    }
    
//    平移结束的时候判断
    if(pan.state == UIGestureRecognizerStateEnded)
    {
        NSLog(@"平移结束");
        if (pan.view.center.x <= KSWidth/8*2)
        {
            [UIView animateWithDuration:0.15 animations:^{
                pan.view.center = CGPointMake(centerX,pan.view.center.y + point.y);
            }];
            hotOrNewState = new;
            [self findAllRealityData:limitNumber];
        }
        else if(pan.view.center.x >KSWidth/8*2)
        {
            [UIView animateWithDuration:0.15 animations:^{
                pan.view.center = CGPointMake(centerX*3,pan.view.center.y + point.y);
            }];
            hotOrNewState = hot;
            [self findAllRealityData:limitNumber];
        }
        
    }
////    重置坐标
    RealityHeader *header = [_tableView dequeueReusableHeaderFooterViewWithIdentifier:@"header"];
    [pan setTranslation:CGPointZero inView:header.whiteView];
}

// 弹出视图
- (void)alertActionWithTitle:(NSString *)title message:(NSString *)message other:(NSString *)other
{
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *otherAction = [UIAlertAction actionWithTitle:other style:UIAlertActionStyleDefault handler:nil];
    [alertVc addAction:otherAction];
    [self presentViewController:alertVc animated:YES completion:nil];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
